<template>
  <view class="layout">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="statusBar" :style="{ height: getStatusBarHeight() + 'px' }"></view>
      <view class="titleBar" :style="{ 
        height: getTitleBarHeight() + 'px', 
        paddingLeft: getLeftIconLeft() + 'px' 
      }">
        <view class="nav-content">
          <uni-icons 
            type="back" 
            size="28" 
            color="#000" 
            class="back-icon"
            @click="onBack"
          />
          <view class="title-section">
            <text class="title">黄增平</text>
          </view>
          <uni-icons 
            type="trash"
            size="28" 
            color="#000" 
            class="delete-icon"
            @click="showDeleteConfirm"
          />
        </view>
      </view>
    </view>
    
    <view class="fill" :style="{ height: getNavBarHeight() + 'px' }"></view>
    
    <!-- 聊天内容区域 -->
    <scroll-view 
      class="chat-list" 
      scroll-y 
      :show-scrollbar="false" 
      :style="{ height: `calc(100vh - ${getNavBarHeight() + 65}px)` }"
      :scroll-into-view="scrollToMsgId"
      scroll-with-animation
    >
      <view 
        class="chat-item" 
        v-for="(item, index) in chats" 
        :key="index"
        :id="'msg-' + index"
      >
        <!-- 两条消息之间的间隔时间戳 -->
        <view v-if="shouldShowTimestamp(index)" class="times">
          {{ getMessageTimestamp(index) || '刚刚' }}
        </view>
        
        <!-- 左边消息 -->
        <view class="left" v-if="item.userId === 2">
          <image class="avatar" src="/static/test/1.jpg" @click="goDetail"></image>
          <view class="message-content" v-if="item.type === 'text'">
            <text class="message-text" @longpress="copyMessage(item.content)">{{ item.content }}</text>
          </view>
          <image 
            :src="item.image" 
            v-if="item.type === 'image'" 
            class="message-image left-image"
            @click="previewImage(item.image)"
            mode="heightFix"
          ></image>
          <!-- 发送的是文件 -->
          <view class="file" v-if="item.type === 'file'">
            <view class="file-name">{{item.file.name}}</view>
            <image :src="item.file.image"></image>
          </view>
          <!-- 发送的是语音 -->
          <view class="audio" v-if="item.type === 'audio'">
            <view class="audio-bubble" @click="playAudio(item)">
              <view class="voice-wave">
                <view class="voice-bar"></view>
                <view class="voice-bar"></view>
                <view class="voice-bar"></view>
              </view>
              <view class="voice-time">"{{item.audio.duration}}</view>
            </view>
          </view>
        </view>
        
        <!-- 右边消息 -->
        <view class="right" v-if="item.userId === 1">
          <view class="message-content" v-if="item.type === 'text'">
            <text class="message-text" @longpress="copyMessage(item.content)">{{ item.content }}</text>
          </view>
          <image 
            :src="item.image" 
            v-if="item.type === 'image'" 
            class="message-image right-image"
            @click="previewImage(item.image)"
            mode="heightFix"
          ></image>
          <!-- 发送的是文件 -->
          <view class="file" v-if="item.type === 'file'">
            <view class="file-name">{{item.file.name}}</view>
            <image :src="item.file.image"></image>
          </view>
          <!-- 发送的是语音 -->
          <view class="audio" v-if="item.type === 'audio'">
            <view class="audio-bubble" @click="playAudio(item)">
              <view class="voice-time">{{item.audio.duration}}"</view>
              <view class="voice-wave" style="margin-left: 10rpx; margin-right: -10prx;">
                <view class="voice-bar"></view>
                <view class="voice-bar"></view>
                <view class="voice-bar"></view>
              </view>
            </view>
          </view>
          <image class="avatar" src="/static/test/2.jpg"></image>
        </view>
      </view>
    </scroll-view>
   
    <!-- 底部导航栏 -->
    <view class="bottom" :style="{ transform: isPopupShow ? 'translateY(-' + popupHeight + 'px)' : (isEmojiPopupShow ? 'translateY(-' + emojiPopupHeight + 'px)' : 'translateY(0)') }">
      <!-- 语音/键盘切换图标 -->
      <image 
        :src="isVoiceMode ? '/static/chat/keyboard.png' : '/static/chat/voice.png'" 
        mode="aspectFit" 
        class="bottom-icon" 
        @click="toggleVoiceMode" 
      />
      <!-- 输入框或按住说话区域 -->
      <view 
        v-if="isVoiceMode" 
        class="hold-speak" 
        @touchstart="handleTouchStart" 
        @touchend="handleTouchEnd"
      >
        按住 说话
      </view>
      <input 
        v-else
        v-model="inputValue"
        placeholder="请输入内容..." 
        class="custom-input"
        @focus="onInputFocus"
        @blur="onInputBlur"
        @keydown.enter="sendMessage"
      />
      <image src="/static/chat/b.png" mode="aspectFit" class="bottom-icon" @click="toggleEmojiPopup" />
      <image src="/static/chat/add.png" mode="aspectFit" class="bottom-icon" @click="togglePopup" />
    </view>

    <!-- 加号弹出层盒子 -->
    <view class="popup-box" :class="{'show': isPopupShow, 'hide': !isPopupShow}" :style="{ height: popupHeight + 'px' }">
      <view class="popup-content">
        <view class="popup-group">
          <view class="popup-item" @click="onPopupItemClick('album')">
            <image src="/static/chat/photo.png" mode="aspectFit" class="popup-icon" />
            <text class="popup-text">相册</text>
          </view>
          <view class="popup-item" @click="onPopupItemClick('file')">
            <image src="/static/chat/file.png" mode="aspectFit" class="popup-icon" />
            <text class="popup-text">文件</text>
          </view>
          <view class="popup-item" @click="onPopupItemClick('location')">
            <image src="/static/chat/location.png" mode="aspectFit" class="popup-icon" />
            <text class="popup-text">位置</text>
          </view>
          <view class="popup-item" @click="onPopupItemClick('voiceInput')">
            <image src="/static/chat/voiceInput.png" mode="aspectFit" class="popup-icon" />
            <text class="popup-text">语音输入</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 表情弹出层盒子 -->
    <view class="emoji-popup-box" :class="{'show': isEmojiPopupShow, 'hide': !isEmojiPopupShow}" :style="{ height: emojiPopupHeight + 'px' }">
      <scroll-view 
        class="emoji-scroll"
        scroll-y
        :show-scrollbar="false" 
      >
        <view class="emoji-content">
          <view 
              class="emoji-item" 
              v-for="(emoji, index) in emojis" 
              :key="index"
              @click="onEmojiItemClick(emoji)"
          >
            <text class="emoji-char">{{ emoji }}</text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, computed } from 'vue'
import { getStatusBarHeight, getTitleBarHeight, getNavBarHeight, getLeftIconLeft } from "@/utils/system.js";
import { emojiList } from "./emoj.js";

// 输入框内容
const inputValue = ref('');
// 是否为语音模式
const isVoiceMode = ref(false);
// 滚动到的消息ID
const scrollToMsgId = ref('');
// 选中的图片临时存储
const selectedImage = ref('');
// 当前播放的语音消息
const currentPlayingAudio = ref(null);
// 复制冷却时间
const lastCopyTime = ref(0);

// 聊天数据（包含完整日期时间）
const chats = ref([
  { userId: 2, content: '嗨，你好！', time: '2025-06-18 10:00', type: 'text' },
  { userId: 1, content: '你好，今天怎么样？', time: '2025-06-18 10:02', type: 'text' },
  { userId: 2, content: '还行，就是有点忙。你呢？', time: '2025-06-18 10:03', type: 'text' },
  { userId: 1, content: '我也是，最近项目比较紧张。', time: '2025-06-18 10:05', type: 'text' },
  { userId: 2, content: '根本看不懂。他那个到底是考原题还是考类似的题？', time: '2025-06-18 10:07', type: 'text' },
  { userId: 1, content: '最近在复习吗？', time: '2025-06-18 10:08', type: 'text' },
  { userId: 2, content: '是啊，准备下个月的考试。', time: '2025-06-18 10:10', type: 'text' },
  { 
    userId: 2, 
    type: 'audio', 
    audio: {
      duration: 15,
      src: 'https://web-ext-storage.dcloud.net.cn/uni-app/ForElise.mp3'
    },
    time: '2025-06-18 10:12' 
  },
  { 
    userId: 1, 
    type: 'audio', 
    audio: {
      duration: 22,
      src: 'https://web-ext-storage.dcloud.net.cn/uni-app/ForElise.mp3'
    },
    time: '2025-06-19 10:13' 
  }
]);

// 格式化时间函数
const formatTime = (date) => {
  if (!date) return null;
  
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hour = date.getHours().toString().padStart(2, '0');
  const minute = date.getMinutes().toString().padStart(2, '0');
  
  return {
    year,
    month,
    day,
    hour,
    minute,
    full: `${year}-${month}-${day} ${hour}:${minute}`
  };
};

// 计算时间间隔并返回显示格式
const getTimeIntervalDisplay = (prevTime, currTime) => {
  try {
    if (!prevTime || !currTime) return '';
    
    const prevDate = new Date(prevTime);
    const currDate = new Date(currTime);
    const timeDiff = currDate - prevDate;
    const minutesDiff = timeDiff / (1000 * 60);
    const daysDiff = timeDiff / (1000 * 60 * 60 * 24);
    const yearsDiff = daysDiff / 365;
    
    const timeObj = formatTime(currDate);
    if (!timeObj) return '';
    
    // 超过5分钟但小于1天：显示时分
    if (minutesDiff > 5 && daysDiff < 1) {
      return `${timeObj.hour}:${timeObj.minute}`;
    }
    // 超过1天但小于1年：显示月日
    else if (daysDiff >= 1 && yearsDiff < 1) {
      return `${timeObj.month}-${timeObj.day}`;
    }
    // 超过1年：显示年月日
    else if (yearsDiff >= 1) {
      return `${timeObj.year}-${timeObj.month}-${timeObj.day}`;
    }
    // 5分钟内：不显示
    else {
      return '';
    }
  } catch (error) {
    console.error('计算时间间隔出错:', error);
    return '';
  }
};

// 判断是否应该显示时间戳
const shouldShowTimestamp = (index) => {
  if (index <= 0 || !chats.value || chats.value.length <= index) return false;
  
  const prevMsg = chats.value[index - 1];
  const currMsg = chats.value[index];
  
  if (!prevMsg || !currMsg || !prevMsg.time || !currMsg.time) return false;
  
  return getTimeIntervalDisplay(prevMsg.time, currMsg.time) !== '';
};

// 获取消息时间戳
const getMessageTimestamp = (index) => {
  if (index <= 0 || !chats.value || chats.value.length <= index) return '';
  
  const prevMsg = chats.value[index - 1];
  const currMsg = chats.value[index];
  
  if (!prevMsg || !currMsg || !prevMsg.time || !currMsg.time) return '';
  
  return getTimeIntervalDisplay(prevMsg.time, currMsg.time);
};

// 返回逻辑
const onBack = () => {
  uni.navigateBack();
};

// 删除确认逻辑
const showDeleteConfirm = () => {
  uni.showModal({
    title: '确认清除',
    content: '是否清除所有对话？',
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '已清除所有对话',
          icon: 'none'
        });
      }
    }
  });
};

// 输入框状态管理
const isFocused = ref(false);
const onInputFocus = () => {
  isFocused.value = true;
  isPopupShow.value = false;
  isEmojiPopupShow.value = false;
};
const onInputBlur = () => {
  isFocused.value = false;
};

// 加号弹出层
const isPopupShow = ref(false);
const popupHeight = ref(200);

const togglePopup = () => {
  isPopupShow.value = !isPopupShow.value;
  isEmojiPopupShow.value = false;
};

// 表情弹出层
const isEmojiPopupShow = ref(false);
const emojiPopupHeight = ref(200);

const toggleEmojiPopup = () => {
  isEmojiPopupShow.value = !isEmojiPopupShow.value;
  isPopupShow.value = false;
};

// 语音/键盘模式切换
const toggleVoiceMode = () => {
  isVoiceMode.value = !isVoiceMode.value;
  isPopupShow.value = false;
  isEmojiPopupShow.value = false;
};

// 按住说话
const handleTouchStart = () => {
  console.log('开始按住说话');
};
const handleTouchEnd = () => {
  console.log('结束按住说话');
};

const emojis = emojiList;

// 表情点击
const onEmojiItemClick = (emoji) => {
  if (!isVoiceMode.value) {
    inputValue.value += emoji;
  }
};

// 预览图片
const previewImage = (imgUrl) => {
  uni.previewImage({
    current: imgUrl,
    urls: [imgUrl]
  });
};

// 加号弹出层项目点击
const onPopupItemClick = (type) => {
  console.log(`选择了: ${type}`);
  togglePopup();
  
  switch(type) {
    case 'album':
      // 选择图片
      uni.chooseImage({
        count: 1, // 一次选择1张图片
        sizeType: ['compressed'], // 压缩图
        sourceType: ['album', 'camera'], // 从相册或相机选择
        success: (res) => {
          // 获取选中的图片路径
          selectedImage.value = res.tempFilePaths[0];
          // 发送图片消息
          sendImageMessage(selectedImage.value);
        }
      });
      break;
    case 'file':
      // 选择文件
      uni.chooseFile({
        count: 1, // 一次选1个文件
        success: (res) => {
          const tempFile = res.tempFiles[0];
          const fileName = tempFile.name;     // 文件名
          const fileType = fileName.split('.').pop();  // 文件后缀（用于判断图标）
          const localPath = tempFile.path; // 本地临时路径

          // 生成文件类型图标（可根据后缀自定义）
          const fileTypeIcon = getFileTypeIcon(fileType);

          // 发送文件消息到聊天列表
          sendFileMessage({
            name: fileName,
            type: fileType,
            image: fileTypeIcon, 
            localPath: localPath 
          });
        }
      });
      break;
    case 'location':
      uni.getLocation({ type: 'gcj02' });
      break;
    case 'voiceInput':
      console.log('语音输入');
      break;
  }
};

// 发送文件消息到聊天列表
const sendFileMessage = (fileInfo) => {
  const newMsgIndex = chats.value.length;
  const newMsgId = 'msg-' + newMsgIndex;

  // 添加文件消息到聊天列表
  chats.value.push({
    userId: 1,
    type: 'file', // 标记为文件类型
    file: {
      name: fileInfo.name,
      image: fileInfo.image, // 文件类型图标
      localPath: fileInfo.localPath // 本地路径
    },
    time: getCurrentTime()
  });

  // 滚动到最新消息
  nextTick(() => {
    scrollToMessage(newMsgId);
  });
};

// 根据文件后缀生成图标
const getFileTypeIcon = (fileType) => {
  const iconMap = {
    pdf: 'https://cdn.nlark.com/yuque/0/2025/png/49723406/1750226194638-c9bc1f59-541a-4dd3-813c-4412af58ad60.png?x-oss-process=image%2Fformat%2Cwebp',
    docx: 'https://cdn.nlark.com/yuque/0/2025/png/49723406/1750226242512-2c48edbd-10da-4545-b64a-8cc395e2c00f.png?x-oss-process=image%2Fformat%2Cwebp',
    ppt: 'https://cdn.nlark.com/yuque/0/2025/png/49723406/1750226173722-a28ed5cf-c713-4340-a5de-04b54f2a0ee8.png?x-oss-process=image%2Fformat%2Cwebp',
    zip: 'https://cdn.nlark.com/yuque/0/2025/png/49723406/1750226324170-61254033-947b-42c6-9895-74c5a029274c.png?x-oss-process=image%2Fformat%2Cwebp',
    txt: 'https://cdn.nlark.com/yuque/0/2025/png/49723406/1750226260905-aa07c44f-786b-43e8-81a7-dfb9ba81764d.png?x-oss-process=image%2Fformat%2Cwebp',
  };
  return iconMap[fileType] || 'https://cdn.nlark.com/yuque/0/2025/png/49723406/1750226356705-406f8052-0c16-433c-9d3c-9d1a5f5a8d56.png?x-oss-process=image%2Fformat%2Cwebp';
};

// 发送图片消息
const sendImageMessage = (imagePath) => {
  const newMsgIndex = chats.value.length;
  const newMsgId = 'msg-' + newMsgIndex;
  
  // 添加图片消息到聊天列表
  chats.value.push({
    userId: 1,
    type: 'image',
    image: imagePath,
    time: getCurrentTime()
  });
  
  // 滚动到最新消息
  nextTick(() => {
    scrollToMessage(newMsgId);
  });
};

// 发送语音消息（示例：模拟发送语音）
const sendVoiceMessage = (duration) => {
  const newMsgIndex = chats.value.length;
  const newMsgId = 'msg-' + newMsgIndex;
  
  // 添加语音消息到聊天列表
  chats.value.push({
    userId: 1,
    type: 'audio',
    audio: {
      duration: duration,
      src: `/static/chat/voice_${duration}.mp3` // 假设语音文件按时长命名
    },
    time: getCurrentTime()
  });
  
  // 滚动到最新消息
  nextTick(() => {
    scrollToMessage(newMsgId);
  });
};

// 格式化时间为 mm:ss 格式
const formatTimeDisplay = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

// 获取当前时间（完整格式）
const getCurrentTime = () => {
  const now = new Date();
  return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
};

// 封装滚动到指定消息的函数
const scrollToMessage = (messageId) => {
  // 先设置目标ID触发滚动
  scrollToMsgId.value = messageId;
  
  // 强制刷新机制，处理某些情况下滚动失效的问题
  setTimeout(() => {
    // 先清空ID
    scrollToMsgId.value = '';
    
    // 等待DOM更新后重新设置ID
    nextTick(() => {
      scrollToMsgId.value = messageId;
    });
  }, 100);
};

// 发送文本消息
const sendMessage = () => {
  if (!inputValue.value.trim()) return;
  
  const newMsgIndex = chats.value.length;
  const newMsgId = 'msg-' + newMsgIndex;
  
  // 添加新消息
  chats.value.push({
    userId: 1,
    content: inputValue.value.trim(),
    type: 'text',
    time: getCurrentTime()
  });
  
  // 清空输入框
  inputValue.value = '';
  
  // 滚动到最新消息
  nextTick(() => {
    scrollToMessage(newMsgId);
  });
};

// 播放语音消息
const playAudio = (msg) => {
  // 停止当前播放的语音
  if (currentPlayingAudio.value && currentPlayingAudio.value !== msg) {
    stopPlayingAudio();
  }
  
  // 创建音频上下文
  const audioContext = uni.createInnerAudioContext();
  audioContext.src = msg.audio.src;
  
  // 添加播放状态样式
  const audioElement = document.getElementById(`msg-${chats.value.indexOf(msg)}`).querySelector('.audio-bubble');
  if (audioElement) {
    audioElement.classList.add('audio-playing');
  }
  
  // 播放完成后移除样式
  audioContext.onEnded = () => {
    if (audioElement) {
      audioElement.classList.remove('audio-playing');
    }
    currentPlayingAudio.value = null;
  };
  
  // 播放音频
  audioContext.play();
  
  // 记录当前播放的语音
  currentPlayingAudio.value = msg;
  
  // 播放结束后清理
  audioContext.onStop = () => {
    if (audioElement) {
      audioElement.classList.remove('audio-playing');
    }
    currentPlayingAudio.value = null;
  };
  
  audioContext.onError = (e) => {
    console.error('音频播放错误:', e);
    if (audioElement) {
      audioElement.classList.remove('audio-playing');
    }
    currentPlayingAudio.value = null;
  };
};

// 停止播放语音
const stopPlayingAudio = () => {
  const audioElements = document.querySelectorAll('.audio-bubble.audio-playing');
  audioElements.forEach(el => {
    el.classList.remove('audio-playing');
  });
};

// 复制消息内容到剪贴板
const copyMessage = (content) => {
  if (!content) return;
  
  const now = Date.now();
  if (now - lastCopyTime.value < 1000) return; // 1秒内不重复复制
  lastCopyTime.value = now;
  
  uni.setClipboardData({
    data: content,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'none',
        duration: 1500
      });
    },
    fail: (err) => {
      console.error('复制失败:', err);
      uni.showToast({
        title: '复制失败',
        icon: 'none',
        duration: 1500
      });
    }
  });
};

onMounted(() => {
  // 初始化时滚动到底部
  if (chats.value.length > 0) {
    scrollToMessage('msg-' + (chats.value.length - 1));
  }
});

// 详情
const goDetail = ()=>{
	uni.navigateTo({
		url:"/pages/chat/details"
	})
}
</script>

<style lang="scss" scoped>
	@import 'dialogue.css';

/* 保留需要作用于当前组件的样式或SCSS变量 */
.layout {
  .navbar {
    .statusBar {
      background-color: #fff;
    }
  }
}
</style>